package com.hugy.test.entity.es;

import cn.hutool.core.collection.CollectionUtil;
import lombok.Data;

import java.io.Serializable;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author YangChao
 * @create 2018-06-02 22:47
 **/
@Data
public class QueryParam implements Serializable, Cloneable {

    private static final long serialVersionUID = 7941767360194797891L;

    /**
     * 是否进行分页，默认为true
     */
    private boolean paging = true;

    /**
     * 第几页 从0开始
     */
    private int pageNo = 0;

    /**
     * 每页显示记录条数
     */
    private int pageSize = 25;

    /**
     * 限制翻滚最大条数
     */
    private int scrollSize;

    /**
     * 限制最大条数
     */
    private int limit;

    /**
     * 条件集合
     */
    protected List<Term> terms = new LinkedList<>();

    /**
     * 排序字段
     */
    private List<Sort> sorts = new LinkedList<>();

    public QueryParam or(String column, Object value) {
        return or(column, TermTypeEnum.EQ, value);
    }

    public QueryParam and(String column, Object value) {
        return and(column, TermTypeEnum.EQ, value);
    }

    public QueryParam or(String column, TermTypeEnum termType, Object value) {
        Term term = new Term();
        term.setTermType(termType);
        term.setColumn(column);
        term.setValue(value);
        term.setType(TermEnum.OR);
        terms.add(term);
        return this;
    }

    public QueryParam and(String column, TermTypeEnum termType, Object value) {
        Term term = new Term();
        term.setTermType(termType);
        term.setColumn(column);
        term.setValue(value);
        term.setType(TermEnum.AND);
        terms.add(term);
        return this;
    }

    public QueryParam addTerm(Term term) {
        terms.add(term);
        return this;
    }

    public QueryParam addTerms(List<Term> terms) {
        if (CollectionUtil.isNotEmpty(terms)) {
            this.terms.addAll(terms);
        }
        return this;
    }

    /**
     * 添加排序
     *
     * @param column
     * @param order
     * @return
     */
    public Sort addSort(String column, SortEnum order) {
        Sort sort = new Sort(column, order);
        sorts.add(sort);
        return sort;
    }

    @Override
    public QueryParam clone() {
        QueryParam sqlParam = new QueryParam();
        List<Term> terms = this.terms.stream().map(Term::clone).collect(Collectors.toList());
        sqlParam.setTerms(terms);
        sqlParam.setPageNo(pageNo);
        sqlParam.setPageSize(pageSize);
        sqlParam.setSorts(sorts);
        return sqlParam;
    }

}
